<template>
  <div>
    <div>
      <we-button
        v-if="baseCode"
        @click="addWinShow"
        type="primary"
        size="small"
      >
        <em class="el-icon-plus"></em> 新增
      </we-button>
      <we-button
        v-if="baseCode"
        @click="handleClick(currentRow)"
        type="primary"
        size="mini"
      >
        <em class="el-icon-edit"></em> 修改
      </we-button>
      <we-button v-if="baseCode" @click="deleteRow" type="primary" size="mini">
        <em class="el-icon-delete"></em> 删除
      </we-button>
      <span v-if="baseName">当前人员：【 {{baseName}} 】</span>
    </div>

    <!-- 表格 ↓↓↓↓↓↓↓↓↓↓ -->
    <el-table
      size="mini"
      :header-cell-style="rowClass"
      :data="tableData"
      height="116px"
      border
      highlight-current-row
      resizable
      ref="singleTable"
      @row-dblclick="handleClick"
      @current-change="handleCurrentChange"
      style="width: 100%; margin-top: 5px"
    >
      <el-table-column type="index" label="#"> </el-table-column>
      <el-table-column
        prop="goTime"
        width="150"
        :show-overflow-tooltip="true"
        label="出国(出境)日期"
      >
      </el-table-column>
      <el-table-column
        prop="purpose_dictText"
        width="150"
        :show-overflow-tooltip="true"
        label="出国(出境)目的"
      >
      </el-table-column>
      <el-table-column
        prop="dispatchUnit"
        width="150"
        :show-overflow-tooltip="true"
        label="派出单位"
      >
      </el-table-column>
      <el-table-column
        prop="goUnit"
        :show-overflow-tooltip="true"
        width="150"
        label="所去单位"
      >
      </el-table-column>
      <el-table-column
        prop="fundsSource_dictText"
        :show-overflow-tooltip="true"
        width="150"
        label="经费来源"
      >
      </el-table-column>
      <el-table-column
        prop="goCountry_dictText"
        :show-overflow-tooltip="true"
        width="150"
        label="所去国家(地区)"
      >
      </el-table-column>
      <el-table-column
        prop="groupName"
        :show-overflow-tooltip="true"
        width="150"
        label="团组名称"
      >
      </el-table-column>
      <el-table-column
        prop="approvalUnit"
        :show-overflow-tooltip="true"
        width="150"
        label="审批单位"
      >
      </el-table-column>
      <el-table-column
        prop="approvalNumber"
        :show-overflow-tooltip="true"
        width="150"
        label="审批文号"
      >
      </el-table-column>
      <el-table-column
        prop="backTime"
        :show-overflow-tooltip="true"
        width="150"
        label="回国日期"
      >
      </el-table-column>
      <el-table-column
        prop="daysAbroad"
        :show-overflow-tooltip="true"
        width="150"
        label="出国天数"
      >
      </el-table-column>
      <!-- <el-table-column fixed="right" label="操作" width="180">
        <template slot-scope="scope">
          <we-button @click="handleClick(scope.row)" type="primary" size="mini"
            >详 情</we-button
          >
          <we-button type="danger" size="mini" @click="deleteSh(scope.row)" >删 除</we-button>
        </template>
      </el-table-column> -->
    </el-table>
    <div class="table_tools">
      <we-Pagination
        :page="pagination.pageNum"
        :pageSize="pagination.pageSize"
        :total="pagination.total"
        @currentChange="currentChange($event)"
        >></we-Pagination
      >
    </div>
    <!-- 表格 ↑↑↑↑↑↑↑↑↑↑-->

    <!-- 新增弹窗↓↓↓↓↓↓ -->
    <el-dialog
      title="出国(出境)子集"
      :visible.sync="dialogFormVisible"
      @close="handleOffDialog"
      append-to-body
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="140px"
        size="mini"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出国(出境)日期" prop="goTime">
              <el-date-picker
                class="inputW"
                v-model="ruleForm.goTime"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出国(出境)目的" prop="purpose">
              <el-select
                class="inputW"
                v-model="ruleForm.purpose"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="item in goingPurpose"
                  :key="item.uuid"
                  :label="item.name"
                  :value="item.uuid"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="派出单位" prop="dispatchUnit">
              <el-input
                class="inputW"
                v-model="ruleForm.dispatchUnit"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所去单位" prop="goUnit">
              <el-input
                class="inputW"
                v-model="ruleForm.goUnit"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="经费来源" prop="fundsSource">
              <el-select
                class="inputW"
                v-model="ruleForm.fundsSource"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="item in sourceFunds"
                  :key="item.uuid"
                  :label="item.name"
                  :value="item.uuid"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所去国家(地区)" prop="goCountry">
              <el-select
                class="inputW"
                v-model="ruleForm.goCountry"
                placeholder="请选择"
                clearable
                filterable
              >
                <el-option
                  v-for="item in allCountry"
                  :key="item.uuid"
                  :label="item.countryName"
                  :value="item.uuid"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="团组名称" prop="groupName">
              <el-input
                class="inputW"
                v-model="ruleForm.groupName"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审批单位" prop="approvalUnit">
              <el-input
                class="inputW"
                v-model="ruleForm.approvalUnit"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="审批文号" prop="approvalNumber">
              <el-input
                class="inputW"
                v-model="ruleForm.approvalNumber"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="回国日期" prop="backTime">
              <el-date-picker
                class="inputW"
                v-model="ruleForm.backTime"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出国天数" prop="daysAbroad" :required="true">
              <el-input
                class="inputW"
                v-model.number="ruleForm.daysAbroad"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <we-button size="small" @click="handleOffDialog"
          >取 消</we-button
        >
        <we-button size="small" type="primary" @click="submitForm('ruleForm')"
          >新 增</we-button
        >
      </div>
    </el-dialog>
    <!-- 新增弹窗↑↑↑↑↑↑ -->

    <!-- 编辑弹窗↓↓↓↓↓↓ -->
    <el-dialog
      title="出国(出境)子集"
      :visible.sync="dialogVisible"
      append-to-body
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="140px"
        size="mini"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出国(出境)日期" prop="goTime">
              <el-date-picker
                class="inputW"
                v-model="ruleForm.goTime"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出国(出境)目的" prop="purpose">
              <el-select
                class="inputW"
                v-model="ruleForm.purpose"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="item in goingPurpose"
                  :key="item.uuid"
                  :label="item.name"
                  :value="item.uuid"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="派出单位" prop="dispatchUnit">
              <el-input
                class="inputW"
                v-model="ruleForm.dispatchUnit"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所去单位" prop="goUnit">
              <el-input
                class="inputW"
                v-model="ruleForm.goUnit"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="经费来源" prop="fundsSource">
              <el-select
                class="inputW"
                v-model="ruleForm.fundsSource"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="item in sourceFunds"
                  :key="item.uuid"
                  :label="item.name"
                  :value="item.uuid"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所去国家(地区)" prop="goCountry">
              <el-select
                class="inputW"
                v-model="ruleForm.goCountry"
                placeholder="请选择"
                clearable
                filterable
              >
                <el-option
                  v-for="item in allCountry"
                  :key="item.uuid"
                  :label="item.countryName"
                  :value="item.uuid"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="团组名称" prop="groupName">
              <el-input
                class="inputW"
                v-model="ruleForm.groupName"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审批单位" prop="approvalUnit">
              <el-input
                class="inputW"
                v-model="ruleForm.approvalUnit"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="审批文号" prop="approvalNumber">
              <el-input
                class="inputW"
                v-model="ruleForm.approvalNumber"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="回国日期" prop="backTime">
              <el-date-picker
                class="inputW"
                v-model="ruleForm.backTime"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出国天数" prop="daysAbroad" :required="true">
              <el-input
                class="inputW"
                v-model.number="ruleForm.daysAbroad"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <we-button size="small" @click="dialogVisible = false">取 消</we-button>
        <we-button size="small" type="primary" @click="updRe('ruleForm')"
          >编 辑</we-button
        >
      </div>
    </el-dialog>
    <!-- 编辑弹窗↑↑↑↑↑↑ -->
  </div>
</template>

<script>
import WeButton from "@/components/WeButton";
import WePagination from "@/components/WePagination";
import { getAction, postAction, deleteAction, putAction } from "@/api/manage";
import {bus} from "@/utils/eventBus";
import {opDictNew} from "@/api/apiUrl";
export default {
  components: {
    WeButton,
    WePagination,
  },
  data() {
    const checkDaysAbroad = (rule, value, callback) => {
      if (!Number.isInteger(value)) {
        callback(new Error("请输入数字值"));
      } else {
        callback();
      }
    };
    return {
      selListParameter: { baseCode: "" }, // 列表查询参数
      pagination: {
        total: 10, // 总数据条数
        pageSize: 10, // 每页条数
        pageNum: 1, // 当前页
      }, // 列表分页数据
      tableData: [],
      dialogFormVisible: false,
      dialogVisible: false,
      currentRow: null,
      ruleForm: {
        goTime: "",
        purpose: "",
        dispatchUnit: "",
        goUnit: "",
        fundsSource: "",
        goCountry: "",
        groupName: "",
        approvalUnit: "",
        approvalNumber: "",
        backTime: "",
        daysAbroad: "",
        uuidList:[],
      },
      rules: {
        goTime: [
          {
            required: true,
            message: "请选择出国(出境)日期",
            trigger: "change",
          },
        ],
        purpose: [
          {
            required: true,
            message: "请选择出国(出境)目的",
            trigger: "change",
          },
        ],
        goCountry: [
          {
            required: true,
            message: "请选择所去国家(地区)",
            trigger: "change",
          },
        ],
        backTime: [
          { required: true, message: "请选择回国日期", trigger: "change" },
        ],
        daysAbroad: [{ validator: checkDaysAbroad, trigger: "blur" }],
      },

      options: [],
      goingPurpose: [], // 出国(出境)目的
      sourceFunds: [], // 经费来源
      allCountry: [], // 国家地区
      baseCode: "",
      baseName: "",
    };
  },
  watch: {
    dialogFormVisible() {
      if (this.dialogFormVisible === false) {
        if (this.$store.state.goingAbroad === true) {
          this.$store.commit("changeGoingAbroad", false);
        }
      }
    },
    dialogVisible() {
      if (this.dialogVisible === false) {
        if (this.$store.state.goingAbroad === true) {
          this.$store.commit("changeGoingAbroad", false);
        }
      }
    },
    "$store.state.baseCode"(newval) {
      this.baseCode = newval;
      this.getList();
    },
    '$store.state.baseName'(newval) {
      this.baseName  = newval
    },
    "$store.state.goingAbroad"(newval) {
      if (newval === true) {
        if (this.$store.state.updateSubset === true) {
          this.dialogVisible = true;
        } else {
          this.dialogFormVisible = true;
        }
        this.$store.commit("changeUpdateSubset", false);
        this.baseCode = this.$store.state.baseCodes;
        this.getGoingPurpose();
        this.getSourceFunds();
        this.getAllCountry();
      }
    },
  },
  methods: {
    clickSubset() {
      this.baseCode = this.$store.state.baseCode;
      this.getGoingPurpose();
      this.getSourceFunds();
      this.getAllCountry();
      this.getList();
    },
    batchAdd(data){
      this.dialogFormVisible = true
      this.ruleForm.uuidList = data
    },
    /**
     * 查询列表
     */
    getList() {
      let self = this;
      const dataZ = this.selListParameter;
      dataZ.baseCode = this.baseCode;
      dataZ.size = this.pagination.pageSize;
      dataZ.page = this.pagination.pageNum;
      postAction("/opGoingAbroad/opGoingAbroadSearch", dataZ)
        .then((result) => {
          // if (!result.data.list.length && this.pagination.pageNum !== 1) {
          //   this.pagination.pageNum -= 1
          //   this.getList()
          // }
          self.pagination.total = result.data.total;
          self.tableData = result.data.list;
        })
        .catch(() => {});
    },

    /*
     * 新增窗展示
     */
    addWinShow() {
      this.thatFormClean();
      this.dialogFormVisible = true;
    },

    /*
     * 新增
     */
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const data = this.ruleForm;
          data.baseCode = this.baseCode;
          data.createUser = "测试员";
          data.sysOrgCode = "测试部门";
          if (this.$store.state.goingAbroad === true) {
            for (let i = 0; i < this.baseCode.length; i++) {
              data.baseCode = this.baseCode[i];
              postAction("/opGoingAbroad/add", data).then((result) => {
                if (result.code === 200) {
                  this.thatFormClean();
                  this.dialogFormVisible = false;
                  bus.$emit('handleDialog')
                  this.thatMessage("新增成功!", "success");
                } else {
                  this.thatMessage(result.msg, "success");
                }
              });
            }
          } else {
            postAction("/opGoingAbroad/add", data).then((result) => {
              if (result.code === 200) {
                this.getList();
                this.thatFormClean();
                this.dialogFormVisible = false;
                bus.$emit('handleDialog')
                this.thatMessage("新增成功!", "success");
              } else {
                this.thatMessage(result.msg, "success");
              }
            });
          }
        } else {
          return false;
        }
      });
    },

    /**
     * 编辑窗打开
     */
    handleClick(row) {
      if (!row) {
        this.$message("请选择要编辑的数据！");
        return;
      }
      this.ruleForm = JSON.parse(JSON.stringify(row));
      this.dialogVisible = true;
    },

    /**
     *编辑点击
     */
    updRe(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          const data = JSON.parse(JSON.stringify(this.ruleForm));
          data.updateUser = "0a590ef720f44d96ab5bebf3c7db0de3";
          postAction("/opGoingAbroad/update", data)
            .then((result) => {
              if (result.code === 200) {
                this.dialogVisible = false;
                bus.$emit('handleDialog')
                this.thatMessage("操作成功", "success");
                this.getList();
              } else {
                this.thatMessage(result.msg, "warning");
              }
            })
            .catch(() => {
              this.thatMessage("操作失败", "warning");
            });
        }
      });
    },
    handleOffDialog() {
      this.dialogFormVisible = false
      bus.$emit('handleDialog')
    },
    handleCurrentChange(val) {
      this.currentRow = val;
    },
    /**
     * 删除
     */
    deleteRow(row) {
      if (!this.currentRow) {
        this.$message("请选择要删除的数据！");
        return;
      }
      this.$confirm("是否要删除这条数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteAction("/opGoingAbroad/delete", {
            uuids: [this.currentRow.uuid],
          }).then((res) => {
            if (res.code === 200) {
              this.thatMessage("删除成功", "success");
              this.getList();
            } else {
              this.thatMessage("操作失败", "warning");
            }
          });
        })
        .catch(() => {
          this.thatMessage("已取消删除", "info");
        });
    },

    /**
     * 查询国家
     */
    getGoingAbroad() {
      postAction("/opGoingAbroad/opGoingAbroadSearch", {
        baseCode: "0a590ef720f44d96ab5bebf3c7db0de3",
      }).then((result) => {
        if (result.code === 200) {
          this.tableData = result.data;
        }
      });
    },

    /**
     * 查询国家
     */
    getAllCountry() {
      getAction("/country/getAllCountry").then((res) => {
        if (res.code === 200) {
          this.allCountry = res.data;
        }
      });
    },

    /**
     * 获取出国(出境)目的
     */
    async getGoingPurpose() {
      // const result = await getAction('/opDictItem/getDictItemListByCode', {
      //   code: 'going_purpose'
      // })
      // this.goingPurpose = result.data.list
      const result = await getAction(`${opDictNew.findTreeByType}?type=rs_br`)
      this.goingPurpose = result.data;
    },

    /**
     * 获取经费来源
     */
    async getSourceFunds() {
      // const result = await getAction('/opDictItem/getDictItemListByCode', {
      //   code: 'source_funds'
      // })
      // this.sourceFunds = result.data.list
      const result = await getAction(`${opDictNew.findTreeByType}?type=rs_ch`)
      this.sourceFunds = result.data;
    },

    rowClass({ row, rowIndex }) {
      return "background:rgba(248, 248, 249, 1);color:#000;";
    },
    handleChange() {},
    handleClose() {},

    // 当前页改变
    currentChange(event) {
      this.pagination.pageNum = event;
      this.getList();
    },

    // 本页面弹窗
    thatMessage(message, type) {
      this.$message({
        message: message,
        type: type,
      });
    },

    // 清空form
    thatFormClean() {
      this.ruleForm = {
        goTime: "",
        purpose: "",
        dispatchUnit: "",
        goUnit: "",
        fundsSource: "",
        goCountry: "",
        groupName: "",
        approvalUnit: "",
        approvalNumber: "",
        backTime: "",
        daysAbroad: "",
        uuid: "",
        baseCode: "",
        sysOrgCode: "",
        createUser: "",
      };
    },
  },
};
</script>

<style scoped>
.table_tools {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
